<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>首页管理规则</span>
        </div>
      </template>
      <el-form :model="homeRole" label-width="120px">
        <el-form-item label="新书数量">
          <el-input v-model="homeRole.homeBookNewNumber" type="number" />
        </el-form-item>
        <el-form-item label="随机推荐书数量">
          <el-input v-model="homeRole.homeBookRandomNumber" type="number" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveOrUpdateHomeRole">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>轮播图管理</span>
        </div>
      </template>
      <div v-if="carouselFiles.length > 0">
        <div v-for="(carousel, index) in carouselFiles" :key="index" class="carousel-item">
          <el-image :src="carousel.url" alt="carousel" style="width: 100px; height: 100px;" />
          <span>{{ carousel.name }}</span>
        </div>
      </div>
      <div v-else>
        <p>暂无轮播图</p>
      </div>
      <el-button type="primary" @click="openUploadDialog">上传轮播图</el-button>
    </el-card>

    <!-- 上传轮播图弹窗 -->
    <el-dialog title="上传轮播图" v-model="dialogVisible" width="30%">
      <el-form :model="uploadForm" label-width="120px">
        <el-form-item label="轮播图序号">
          <el-select v-model="uploadForm.carouselIndex" placeholder="请选择轮播图序号">
            <el-option label="1" value="1" />
            <el-option label="2" value="2" />
            <el-option label="3" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            ref="upload"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange"
          >
            <el-button slot="trigger" type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUpload">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '../utils/axios';
import { ElMessage } from "element-plus";

const homeRole = ref({
  homeBookNewNumber: 0,
  homeBookRandomNumber: 0,
  homeCarousel1: '',
  homeCarousel2: '',
  homeCarousel3: ''
});

const carouselFiles = ref([]);
const dialogVisible = ref(false);
const uploadForm = ref({
  carouselIndex: '',
  file: null
});
const upload = ref(null);

const fetchHomeRole = async () => {
  try {
    const response = await http.get('/home/role');
    if (response.code === 200) {
      homeRole.value.homeBookNewNumber = response.data.homeBookNewNumber;
      homeRole.value.homeBookRandomNumber = response.data.homeBookRandomNumber;
      homeRole.value.homeCarousel1 = response.data.homeCarousel1;
      homeRole.value.homeCarousel2 = response.data.homeCarousel2;
      homeRole.value.homeCarousel3 = response.data.homeCarousel3;
      fetchCarousels();
    } else {
      ElMessage.error(response.data);
    }
  } catch (error) {
    ElMessage.error('获取首页管理规则时发生异常');
  }
};

const saveOrUpdateHomeRole = async () => {
  try {
    const response = await http.put('/home/role', homeRole.value);
    if (response.code === 200) {
      ElMessage.success('保存或更新首页管理规则成功');
    } else {
      ElMessage.error(response.data);
    }
  } catch (error) {
    ElMessage.error('保存或更新首页管理规则时发生异常');
  }
};

const fetchCarousels = () => {
  carouselFiles.value = [
    { url: getImageUrl(homeRole.value.homeCarousel1), name: '轮播图 1' },
    { url: getImageUrl(homeRole.value.homeCarousel2), name: '轮播图 2' },
    { url: getImageUrl(homeRole.value.homeCarousel3), name: '轮播图 3' }
  ].filter(carousel => carousel.url);
};

const openUploadDialog = () => {
  dialogVisible.value = true;
};

const handleChange = (file) => {
  uploadForm.value.file = file.raw;
};

const submitUpload = () => {
  if (!uploadForm.value.carouselIndex) {
    ElMessage.error('请选择轮播图序号');
    return;
  }
  if (!uploadForm.value.file) {
    ElMessage.error('请选择上传的图片');
    return;
  }
  const formData = new FormData();
  formData.append('file', uploadForm.value.file);
  formData.append('carouselIndex', uploadForm.value.carouselIndex);

  http.put('/home/uploadCarousel', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(response => {
    if (response.code === 200) {
      ElMessage.success('轮播图上传成功');
      fetchHomeRole(); // 刷新轮播图列表
      dialogVisible.value = false;
    } else {
      ElMessage.error(response.data);
    }
  })
  .catch(error => {
    ElMessage.error('上传轮播图时发生异常');
  });
};

const getImageUrl = (imageName) => {
  if (imageName) {
    return `http://localhost:8080/book/image/${imageName}`;
  }
  return 'http://localhost:8080/book/image/null.jpg'; // 如果没有封面，则返回默认图片
};

onMounted(() => {
  fetchHomeRole();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 480px;
  margin-bottom: 20px;
}

.carousel-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.carousel-item span {
  margin-left: 10px;
}
</style>
